package lq.book.service;

import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lq.book.bean.User;

public class CookieCheck extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public CookieCheck() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
			{
		  BookService bs=new BookService();
		  HttpSession session=request.getSession();
		  User user=new User();
		  Cookie[] cs =request.getCookies();
		  Cookie name0=null;
		  Cookie pass0=null;
		  for(int i=0;cs!=null&&i<cs.length;i++)
		  {
			  if(cs[i].getName().equals("name"))
			  {
				name0=cs[i];
			  }if(cs[i].getName().equals("pass"))
			  {
				 pass0=cs[i];
			  }
			  
		  }
		 if(name0!=null&pass0!=null)
		  {
                if(bs.checkUser(name0.getValue(), pass0.getValue())!=0)
                {
                  
                   //user.setUsername(username);
               	  // user.setId(1);
               	   //user.setAge(20); 
               	   session.setAttribute("user",user);
               	   response.sendRedirect("ShowBook");
                	
                }
			 
			 
		  }else 
		  {
			  response.sendRedirect("Login.jsp");
			  
		  }
	             
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
